<?php 
/**
* 上传类
*/
class Upload 
{

	public $config = array(
			'UPLOAD_PATH'=>'./Upload/',
			'UPLOAD_NAME'=>'uniqid',
			'UPLOAD_TYPE'=>'.jpg,.png,.gif',
			'UPLOAD_MAX_FILE_SIZE'=>'5000000',
		);
	
	function __construct($config = array())
	{

		foreach ($this->config as $key => $value) {
			$this->config[$key] = isset($config[$key]) ? $config[$key] : $this->config[$key];
		}

		
		
	}

	public function save()
	{
		$fileArr = current($_FILES);

		//重组数据
		$fileList = $this->_reform($fileArr);

		// 检查是否符合条件
		$this->_check($fileList);

		// 移动数据
		$this->_move($fileList);

	}
	/*
	重组数组
	*/
	public function _reform($fileArr)
	{
		$fileList = array();

		foreach ($fileArr as $key => $value) {
			foreach ($value as $k => $v) {
				$fileList[$k][$key]=$v;
			}
		}

		return $fileList;
	}
	/*
	移动数组
	*/
	public function _move($fileList)
	{
		foreach ($fileList as $key =>  $file) {
			// 获取临时文件和原文件名
			$tmp_name = $file['tmp_name'];
			$name = $file['name'];

			// 判断是否合法上传文件
			if(!is_uploaded_file($tmp_name)) exit;

			//设置上传目录
			$path = $this->config['UPLOAD_PATH'];

			// 判断创建目录
			is_dir($path) || mkdir($path);

			// 组合新名
			$newName = uniqid($key).substr($name,strrpos($name, '.'));

			// 组合新路径
			$newPath = $path.$newName;

			// 移动临时文件
			move_uploaded_file($tmp_name,$newPath);
		}
	}

	public function _check($fileList)
	{

		foreach ($fileList as  $value) {
			if($value['size']>$this->config['UPLOAD_MAX_FILE_SIZE']){
				echo '上传失败，不符合条件';
				exit;
			}

			$suffix = substr($value['name'],strrpos($value['name'], '.'));

			if(!strstr($this->config['UPLOAD_TYPE'],$suffix)){
				echo '上传失败，上传的后缀为'.$suffix .'，要求的是'.$this->config['UPLOAD_TYPE'];
				exit;
			};
		}
	}
}










 ?>